<?php
/**
 * Created by PhpStorm.
 * User: yafex
 * Date: 2021/3/31
 * Time: 14:26
 */

class serv_rep_baidu extends L {

    /**
     * 描述 : 百度翻译
     * 作者 : 橙子
     */
    public static function baiduFanyi($content = '', $to = 'zh') {
        !empty($_POST['content']) && $content = $_POST['content'];
        !empty($_POST['to']) && $to = $_POST['to'];
        if(empty($content)){
            return ['state' => 400, 'info' => '参数异常', ];
        }
        $content = html_entity_decode(str_replace('& ', '&', $content));
        //语言自动检测
        $zUrl = "https://fanyi.baidu.com/langdetect";
        $data = array('query' => !empty($content) ? substr($content, 0, 50) : '',);
        $res = of_base_com_net::request($zUrl, array('post' => $data,));
        if (!$res['state']) {
            return ['state' => 301, 'info' => '翻译失败', 'data' => $content];
        }

        $info = json_decode($res['response'], true);
        //原文
        $from = !empty($info['lan']) ? $info['lan'] : 'en';
        //翻译接口
        $url = "https://fanyi.baidu.com/v2transapi";
        $data = array('from' => $from, 'to' => $to, 'query' => $content, 'simple_means_flag' => '3', 'sign' => '52512.273937',//self::baiduFanyiSign($content),
            'token' => '4018a24aef815e052af2327b8ffd2384','domain'=>'common');
        $res = of_base_com_net::request($url, array('post' => $data, //            'cookie' => $cookie
            'cookie' => 'BIDUPSID=3C3466F4DB8D1722A86CCCAB954696BC; PSTM=1597030372; BAIDUID=3C3466F4DB8D17223319E2453F5B4A93:FG=1; FANYI_WORD_SWITCH=1; REALTIME_TRANS_SWITCH=1; SOUND_SPD_SWITCH=1; HISTORY_SWITCH=1; SOUND_PREFER_SWITCH=1; BDUSS_BFESS=DdqclJ4bGRmYUZVVGI2b35aZlEwQ2toOFZBT0k0VjBKRktjODFFREJ-alRkRjlmSUFBQUFBJCQAAAAAAAAAAAEAAABXiyJvxbbIz7~JwcsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANPnN1~T5zdfc; H_WISE_SIDS=148078_156537_155061_157221_158204_157009_156813_156289_150775_154258_155985_148867_156089_154606_151897_153629_156622_157264_155417_157236_150772_151017_156388_156579_156516_127969_154413_154174_146732_155791_131423_155884_153150_154414_157018_107319_156216_154190_156943_155344_157024_156745_157790_144966_157782_154213_157814_156726_155930_147551_158367_158504_158587_157696_154639_154344_110085_157006; MCITY=-%3A; __yjs_duid=1_253b9bad97250ba8807d5f47865982301614829680018; BDSFRCVID_BFESS=ujCOJeC62CE2hxJeV--k8gKqb2hm_EnTH6aoCQqTcurF-AvJGh2oEG0POU8g0KubC1JTogKK3gOTH4PF_2uxOjjg8UtVJeC6EG0Ptf8g0f5; H_BDCLCKID_SF_BFESS=Jbkt_C8-JKvbfP0kjjA_-P4DeP540fRZ5mAqoDQNtf7jjR535jJbe--UKfKHBMTptgQnaIQDtMbzqn-C5fLa-tPFKlKHt5b43bRT-tPy5KJvfj6E3fvvhP-UyNbMWh37JNRlMKoaMp78jR093JO4y4Ldj4oxJpOJ5JbMonLafDD2hDt9e5_Wen_V52T-5-3KbI6f34I8Kb7VbPjYyUnkbfJBDGjeBM7dBKTpaMnzfn3vqJo5qf6nMPI7yajK2-5K5JTaXJ3aK4OaOq-zjt6pQT8r3lAOK5OiJPj2aRTtab3vOIOTXpO1jh8zBN5thURB2DkO-4bCWJ5TMl5jDh3Mb6ksD-FtqjtHtJCHoDKKf-3-fTrd-47oKPcH-UnLq5o33eOZ0l8Ktt3WqM3djPo4DlI7eMJib4jv3nRgVxbmWIQHDpbOL4vnKnDUhajNKjcDbj74KKJxBhCWeIJo5tK-WxPZhUJiB5JMBan7_UJIXKohJh7FM4tW3J0ZyxomtfQxtNRJ0DnjtnLhbC84D5--j5jLep63a43Ka-oa3RTeb6rjDnCrQqohXUI8LPQKt-4fJJCq0xL-0MbkOtn9y4cvyT8sXnO7tfv3LGTj3tThbqj5OhOKbxFMKxL1Db0OhTvMtg3t3DQRLCjoepvoDPJc3Mv30-jdJJQOBKQB0KnGbUQkeq8CQft20b0EeMtjW6LEtbuJoCD5tDL3HJbpq45HMt00qxby26nt2e79aJ5nJDoTsDod2M6q3CrDMN7MBboatDbLMh58QpP-HJ7J0JQx-nLXQmcC-fTx2nryKl0MLp7lbb0xynoDLT_p3MnMBMPe52OnaIbx3fAKftnOM46JehL3346-35543bRTLnLy5KJtMDcnK4-Xj5JLDGoP; H_PS_PSSID=33814_33742_33273_31660_33756_33676_33392_33713_26350; BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; delPer=0; PSINO=2; BAIDUID_BFESS=3F6106C90377691FC89F5DF76DEA8685:FG=1; Hm_lvt_64ecd82404c51e03dc91cb9e8c025574=1616551738,1617172110; Hm_lpvt_64ecd82404c51e03dc91cb9e8c025574=1617172110; ab_sr=1.0.0_M2ZmYzEyOTk1ODhlZWQxY2JiOGY1ZGI3OGY2ZjE5M2IxY2E1NzVlYmJiMTE4YmNiN2NmZGRiZTQxYWM0MTUzMjM4MzA1OGJlN2JmMWE0ZjE0ZDA4MzlhYTI1MjJhMjA1; __yjsv5_shitong=1.0_7_5d6316b9fdfc7a9beca311f0ce0629116616_300_1617172108534_14.21.40.99_233e3093'
        ));
        if ($res['state']) {
            $result = json_decode($res['response'], true);
            $return = '';
            if (isset($result['trans_result']) && is_array($result['trans_result'])) {
                foreach ($result['trans_result']['data'] as $list) {
                    if ($list['dst']) {
                        $return .= $list['dst'] . "\r\n";
                    }
                }
            }
        }
        if(!empty($return)){
            return ['state' => 200, 'info' => '翻译成功', 'data' => $return];
        }else {
            return ['state' => 302, 'info' => '翻译失败', 'data' => $content];
        }
    }

    /**
     * 描述 : 翻译
     * 参数 : POST {
     *          内容 : content
     *          翻译工具 : translator
     *          目标语言 : to
     *      }
     * 返回 : result {
     *          state : 是否请求成功
     *          tgt : 翻译内容
     *      }
     * 作者 : Wade
     */
    public function translate() {
        session_write_close();
        $transResult = array('state' => 0);
        $otherTranslate = isset($_POST['other']) ? $_POST['other'] : '';
        $content = isset($_POST['content']) ? $_POST['content'] : '';
        $content = trim(stripslashes(trim(str_replace('&nbsp;', ' ', $content))), '"');                                 //转换空格去斜线和两端双引
        $sign = isset($_POST['sign']) ? $_POST['sign'] : '';
        if (!empty($content) && !empty($_POST['translator']) && !empty($_POST['to'])) {
            if ($temp = self::translates($content, $_POST['translator'], $_POST['to'], $sign)) {
                if (substr($temp, 0, 3) == pack("CCC", 0xEF, 0xBB, 0xBF)) {
                    $temp = substr($temp, 3);
                }
                $temp = preg_replace('/(^"*)|("$)/i', '', $temp);
                !empty($otherTranslate) && $temp = $content . "\n\n" . $temp;
                $transResult = array('state' => 1, 'tgt' => $temp);
            }
        }
        return $transResult;
    }

    /**
     * 描述 : 翻译接口
     * 参数 :
     *      内容 : content
     *      翻译工具 : translator : (baidu/youdao/bing/google)
     *      目标语言 : to : (cn中文/en英语/ru俄语/pt葡萄牙语/spa西班牙语/fra法语/de德语/it意大利语)
     * 返回 :
     *      翻译内容
     * 作者 : Wade
     */
    public static function translates($content, $translator = 'baidu', $to = 'cn', $sign = '', $tk = '') {
//        $ipUrl = "http://intelligence.yafex.cn/api/?c=proxy&a=getProxy";
//        $ipResult = of_base_com_net::request($ipUrl, array('get' => array(), 'timeout' => 30));
//        if (!empty($ipResult['response'])) {
//            $ipDate = json_decode($ipResult['response'], true);
//            $ipDate = $ipDate['data'];
//        }
        $transResult = false;
        $transTo = array(
            'baidu' => array(
                'cn' => 'zh',
                'en' => 'en',
                'ru' => 'ru',
                'pt' => 'pt',
                'spa' => 'spa',
                'fra' => 'fra',
                'de' => 'de',
                'it' => 'it',
                'jp' => 'jp'
            ),
            'youdao' => array(
                'cn' => 'AUTO2ZH_CN',
                'en' => 'AUTO2EN',
                'ru' => '',
                'pt' => '',
                'spa' => '',
                'fra' => '',
                'de' => '',
                'it' => '',
                'jp' => 'ZH_CN2JA'
            ),
            'bing' => array(
                'cn' => 'zh-CHS',
                'en' => 'EN',
                'ru' => 'RU',
                'pt' => 'PT',
                'spa' => 'ES',
                'fra' => 'fr',
                'de' => 'de',
                'it' => 'it',
                'jp' => 'ja',
                'id' => 'id'
            ),
            'google' => array(
                'cn' => 'zh-CN',
                'en' => 'en',
                'ru' => 'ru',
                'pt' => 'pt',
                'spa' => 'es',
                'fra' => 'fr',
                'de' => 'de',
                'it' => 'it',
                'jp' => 'ja',
                'id' => 'id'
            )
        );
        $to = isset($transTo[$translator][$to]) ? $transTo[$translator][$to] : '';
        if (!empty($content) && !empty($translator) && !empty($to)) {
            switch ($translator) {
                case 'baidu':
                    //                     $result = of_base_com_net::request(
                    //                         'https://fanyi.baidu.com/v2transapi',
                    //                         array(
                    //                             'post' => array(
                    //                                 'query' => $content,
                    //                                 'from' => 'auto',
                    //                                 'to' => $to,
                    //                                 'transtype' => 'realtime',
                    //                                 'simple_means_flag' => 3,
                    //                                 'token' => 'f2d0e1485d2a2d6e0d4a6048c04b4836',
                    //                                 'sign' => !empty($sign) ? $sign : '851205.532020',             //签名
                    //                             ),
                    //                             'cookie' => array(
                    //                                 'BAIDUID' => '4293E22730D9BF0F35E74C492147F49A:FG=1'
                    //                             ),
                    //                             'timeout' => 30
                    //                         )
                    //                     );
                    //                     if ($result['state']) {
                    //                         $response = @iconv('UTF-8', 'UTF-8//IGNORE', $result['response']);
                    //                         $response = json_decode($response, true);
                    //                         $transResult = '';
                    //                         if (isset($response['trans_result']['data'])) {
                    //                             foreach ($response['trans_result']['data'] as $data) {
                    //                                 $transResult .= $data['dst'] . "\n";
                    //                             }
                    //                         }
                    //                     }
                    $transResult = $content;
                    break;
                case 'youdao':
                    $content = str_replace('<br>', "\r\n", $content);
                    $result = of_base_com_net::request('http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc', array(
                        'post' => array(
                            'i' => $content,
                            'type' => $to,
                            'doctype' => 'json',
                            'transtype' => 'trans',
                            'xmlVersion' => 1.6,
                            'keyfrom' => 'fanyi.web',
                            'ue' => 'UTF-8',
                            'typoResult' => true,
                            'flag' => false,
                        ),
                        'header' => array(
                            CURLOPT_PROXY => '',
                            CURLOPT_PROXYPORT => '',
                            CURLOPT_PROXY => '',
                        ),
                        'timeout' => 30
                    ));
                    if ($result['state']) {
                        $response = @iconv('UTF-8', 'UTF-8//IGNORE', $result['response']);
                        $response = json_decode($response, true);
                        $transResult = '';
                        if (isset($response['translateResult'])) {
                            foreach ($response['translateResult'] as $translateResult) {
                                foreach ($translateResult as $data) {
                                    $transResult .= $data['tgt'] . "\n";
                                }
                            }
                        }
                    }
                    break;
                case 'bing':
                    $token = of_base_com_kv::get('bingToken');                                                          //缓存获取token
                    $content = urlencode($content);
                    $resTrans = of_base_com_net::request(                                                               //翻译
                        'http://api.microsofttranslator.com/v2/ajax.svc/Translate', array(
                            'get' => "appId={$token}&text={$content}&to={$to}",
                            'timeout' => 30
                        )
                    );
                    if ($resTrans['state']) {
                        if (preg_match('/ArgumentException: Invalid appId/', $resTrans['response'])) {                  //若token失效
                            $resToken = of_base_com_net::request(                                                       //API获取token
                                'http://www.microsofttranslator.com/ajax/v2/toolkit.ashx', array(
                                    'timeout' => 30,
                                    'header' => [
                                        'X-FORWARDED-FOR: 221.225.193.234',
                                    ]
                                )
                            );
                            if ($resToken['state']) {
                                $start = strpos($resToken['response'], '={appId:') + 9;
                                $length = strpos($resToken['response'], '\',rootURL:') - $start;
                                $token = str_replace('\x', '%', substr($resToken['response'], $start, $length));
                                of_base_com_kv::set('bingToken', $token, 60 * 60 * 12);                                 //设置12小时缓存
                                $resTrans = of_base_com_net::request(                                                   //再翻译
                                    'http://api.microsofttranslator.com/v2/ajax.svc/Translate', array(
                                        'get' => "appId={$token}&text={$content}&to={$to}",
                                        'timeout' => 30
                                    )
                                );
                            }
                        }
                        $transResult = str_replace(array('\u0009', '\u000d'), '', $resTrans['response']);
                        $transResult = stripslashes(str_replace('\u000a', "\n", $transResult));
                    }
                    break;
                case 'google':
                    $tk = '' && $tk = self::googleTk($content);
//                    $header['X-FORWARDED-FOR: '] = !empty($ipDate['proxy']) ? $ipDate['proxy'] : '';
//                    if (!empty($ipDate['userName'])) {
//                        $header['proxy-authorization: '] = $ipDate['userName'] . ':' . $ipDate['passWord'];
//                    }
                    $result = of_base_com_net::request(
                        'https://translate.google.cn/translate_a/t',
                        array(
                            'get' => "client=webapp&sl=auto&tl={$to}&hl={$to}&ie=UTF-8&oe=UTF-8&tk={$tk}",
                            'post' => array(
                                'q' => $content
                            ),
                            'timeout' => 30
                        )
                    );
                    if ($result['state']) {
                        $transResult = json_decode($result['response'], true);
                        $transResult = $transResult[0];
                    }
                    if (!$transResult) {
                        $transResult = self::googleTran($content, $to);
                    }
                    break;
            }
        }
        return $transResult;
    }

    /**
     * 描述 : 谷歌翻译
     * 参数 ：$content 翻译文本 $to 翻译成什么语言
     * 作者 : Smart.Chen
     */
    public static function googleTran($content, $to = 'zh-CN', $num = 0) {
        //2次不成功返回空
        if ($num == 2) {
            return false;
        }
        $ipUrl = "http://intelligence.yafex.cn/api/?c=proxy&a=getProxy";
        $ipResult = of_base_com_net::request($ipUrl, array('get' => array(), 'timeout' => 30));
        if (!empty($ipResult['response'])) {
            $ipDate = json_decode($ipResult['response'], true);
            $ipDate = $ipDate['data'];
        }
        $transResult = false;
        $enText = urlencode($content);
        $url = 'https://translate.google.cn/translate_a/single?client=gtx&dt=t&ie=UTF-8&oe=UTF-8&sl=auto&tl=' . $to . '&q=' . $enText;
        set_time_limit(0);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($ch, CURLOPT_HEADER, false);
        //使用代理
        if (!empty($ipDate)) {
            curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true);
            curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
            curl_setopt($ch, CURLOPT_PROXY, $ipDate['proxy']);
            curl_setopt($ch, CURLOPT_PROXY_SERVICE_NAME, $ipDate['adslAccount']);
            curl_setopt($ch, CURLOPT_PROXYPORT, $ipDate['port']);
            curl_setopt($ch, CURLOPT_PROXYUSERPWD, $ipDate['userName'] . ':' . $ipDate['passWord']);
            //                        curl_setopt($ch, CURLOPT_PROXY, '27.38.98.203');
            //                        curl_setopt($ch, CURLOPT_PROXYPORT, '9797');
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 20);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 40);
        curl_setopt($ch, CURLOPT_URL, $url);
        $result = curl_exec($ch);
        curl_close($ch);
        $result = json_decode($result);
        if (!empty($result)) {
            foreach ($result[0] as $k) {
                $v[] = $k[0];
            }
            $transResult = implode(" ", $v);
        }
        if (!$transResult) {
            $num++;
            return self::googleTran($content, $to, $num);
        }
        return $transResult;
    }

    /**
     * 描述 : 生成谷歌翻译接口 token (来源于网络)
     * 参数 :
     *      需要翻译的内容 : a
     * 返回 :
     *      token
     * 作者 : Wade
     */
    public static function googleTk($a) {
        function shr32($x, $bits) {
            if ($bits <= 0) {
                return $x;
            }
            if ($bits >= 32) {
                return 0;
            }
            $bin = decbin($x);
            $l = strlen($bin);
            if ($l > 32) {
                $bin = substr($bin, $l - 32, 32);
            } else if ($l < 32) {
                $bin = str_pad($bin, 32, '0', STR_PAD_LEFT);
            }
            return bindec(str_pad(substr($bin, 0, 32 - $bits), 32, '0', STR_PAD_LEFT));
        }

        function charCodeAt($str, $index) {
            $char = mb_substr($str, $index, 1, 'UTF-8');
            if (mb_check_encoding($char, 'UTF-8')) {
                $ret = mb_convert_encoding($char, 'UTF-32BE', 'UTF-8');
                return hexdec(bin2hex($ret));
            } else {
                return null;
            }
        }

        function RL($a, $b) {
            for ($c = 0; $c < strlen($b) - 2; $c += 3) {
                $d = $b{$c + 2};
                $d = $d >= 'a' ? charCodeAt($d, 0) - 87 : intval($d);
                $d = $b{$c + 1} == '+' ? shr32($a, $d) : $a << $d;
                $a = $b{$c} == '+' ? ($a + $d & 4294967295) : $a ^ $d;
            }
            return $a;
        }

        $tkk = explode('.', 406398 . '.' . (561666268 + 1526272306));
        $b = $tkk[0];
        for ($d = array(), $e = 0, $f = 0; $f < mb_strlen($a, 'UTF-8'); $f++) {
            $g = charCodeAt($a, $f);
            if (128 > $g) {
                $d [$e++] = $g;
            } else {
                if (2048 > $g) {
                    $d [$e++] = $g >> 6 | 192;
                } else {
                    if (55296 == ($g & 64512) && $f + 1 < mb_strlen($a, 'UTF-8') && 56320 == (charCodeAt($a, $f + 1) & 64512)) {
                        $g = 65536 + (($g & 1023) << 10) + (charCodeAt($a, ++$f) & 1023);
                        $d [$e++] = $g >> 18 | 240;
                        $d [$e++] = $g >> 12 & 63 | 128;
                    } else {
                        $d [$e++] = $g >> 12 | 224;
                        $d [$e++] = $g >> 6 & 63 | 128;
                    }
                }
                $d [$e++] = $g & 63 | 128;
            }
        }
        $a = $b;
        for ($e = 0; $e < count($d); $e++) {
            $a += $d [$e];
            $a = RL($a, '+-a^+6');
        }
        $a = RL($a, "+-3^+b+-f");
        $a ^= $tkk[1];
        if (0 > $a) {
            $a = ($a & 2147483647) + 2147483648;
        }
        $a = fmod($a, pow(10, 6));
        return $a . '.' . ($a ^ $b);
    }


}
return true;